<?php

namespace App\Http\Middleware;

use App\Events\AdminAccessEvent;
use App\Master\Framework\Extend\Module;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminSign
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $prefix = config('admin.prefix');
        if (!Auth::guard('admin')->check()) {
            return redirect("/{$prefix}/passport/logout");
        }

        /*记录用户访问日志*/
        (new AdminAccessEvent());

        $users = auth('admin')->user();

        $logout   = 'login';
        $settings = Module::_SetupModule('SiteSettings');

        if (isset($settings['admin_login']) && $settings['admin_login'] == 'true') {
            if ($users->uuid != session('adminUsersUUID')) {
                $logout = 'logout';
            }
        }
        $params = [
            'logout' => $logout,
        ];
        view()->share($params);

        return $next($request);
    }
}
